package ar.edu.unlu.sistemas.ws.business;

import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

public class QueryHelper {

	private static Collection<String> stopWords;
	
	public static Collection<String> getStopWords() {
		if (stopWords == null) {
			stopWords = new ArrayList<String>();
			try {
				InputStream is = QueryHelper.class.getResourceAsStream("stopwords.txt");
				byte[] bArray = new byte[is.available()];
				is.read(bArray);
				String[] sArray = tokenize(new String(bArray));

				for (int i=0;i<sArray.length;i++) {
					stopWords.add(sArray[i]);
				}
			} catch (Exception e) {
	
			}
		}
		return stopWords;
	}
	
	public static String[] tokenize(String line) throws UnsupportedEncodingException{
		 line = line.toLowerCase();
		 line = line.replaceAll("[óÓòÒôôöÖõÕ]", "o");
		 line = line.replaceAll("[íÍìÌîÎïÏ]", "i");
		 line = line.replaceAll("[áÁàÀâÂÄåÅãÃä]", "a");
		 line = line.replaceAll("[éÉèÈÊêëË]", "e");
		 line = line.replaceAll("[úüÚÜùÙûÛ]", "u");
		 line = line.replaceAll("ñ", "n");
		 line = line.replaceAll("\\W", " ");
		 line = line.replaceAll("[1234567890]"," ");
		 return line.split("\\s+");
	}
	
	public static List<String> indexQuery(String query) {
		List<String> index = new ArrayList<String>();
		try {
			String[] tokens = tokenize(query);
			for (int i=0;i<tokens.length;i++) {
				if (!index.contains(tokens[i]) && !getStopWords().contains(tokens[i])) {
					index.add(tokens[i]);
				}
			}
		} catch (Exception e) {
			
		}
		return index;
	}
	
}
